package com.kyh.util.file;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class FileUtil {
	public static File getFileFromUrl(File file, String urlfile) {
		URL url = null;

		try {
			// 生成文件的url类
			url = new URL(urlfile);
			// 将url链接下的文件以字节流的形式存储到 DataInputStream类中
			DataInputStream dataInputStream = new DataInputStream(url.openStream());
			// 为file生成对应的文件输出流
			FileOutputStream fileOutputStream = new FileOutputStream(file);
			// 定义字节数组大小
			byte[] buffer = new byte[1024];

			// 从所包含的输入流中读取[buffer.length()]的字节，并将它们存储到缓冲区数组buffer 中。
			// dataInputStream.read()会返回写入到buffer的实际长度,若已经读完 则返回-1
			while (dataInputStream.read(buffer) > 0) {
				fileOutputStream.write(buffer);// 将buffer中的字节写入文件中区
			}
			dataInputStream.close();// 关闭输入流
			fileOutputStream.close();// 关闭输出流

			return file;
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}

	/**
	 * AES解码文件
	 * @param key
	 * @param plainFilePath
	 * @param secretFilePath 
	 * @throws Exception
	 */
	public static void decodeAESFile(String key, InputStream is) throws Exception {
		ByteArrayOutputStream bos = null;
		try {
			bos = new ByteArrayOutputStream(is.available());

			byte[] buffer = new byte[1024];
			int count = 0;
			while ((count = is.read(buffer)) != -1) {
				bos.write(buffer, 0, count);
			}
			bos.flush();

			byte[] bytes = decodeAES(key.getBytes(), bos.toByteArray());
			System.out.println(new String(bytes, "utf-8"));

		} catch (Exception e) {
			throw e;
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
				}
			}
			if (bos != null) {
				try {
					bos.close();
				} catch (Exception e) {
				}
			}
		}
	}

	/**
	 * AES����
	 * 
	 * @param key
	 *            ��Կ��Ϣ
	 * @param content
	 *            ��������Ϣ
	 * @return
	 * @throws Exception
	 */
	public static byte[] decodeAES(byte[] key, byte[] content) throws Exception {
		// ����16�ı����ģ�����
		int base = 16;
		if (key.length % base != 0) {
			int groups = key.length / base + (key.length % base != 0 ? 1 : 0);
			byte[] temp = new byte[groups * base];
			Arrays.fill(temp, (byte) 0);
			System.arraycopy(key, 0, temp, 0, key.length);
			key = temp;
		}

		SecretKey secretKey = new SecretKeySpec(key, "AES");
		IvParameterSpec iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0,
				0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
		byte[] tgtBytes = cipher.doFinal(content);
		return tgtBytes;
	}
}
